package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;

    public Client() {
        try {
            System.out.println("客户端连接中");
            socket = new Socket("176.125.111.225",8080);
            System.out.println("客户端连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void start(){
        try {
            ServerHandler heandler = new ServerHandler();
            Thread t = new Thread(heandler::run);
            t.start();

            OutputStream os = socket.getOutputStream();
            OutputStreamWriter ows = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(ows);
            PrintWriter pw = new PrintWriter(bw,true);
            Scanner Scanner = new Scanner(System.in);
            while (true){
                System.out.println("请输入你的昵称:");
                String nickName = Scanner.nextLine();
                if (nickName.trim().isEmpty()){
                    System.out.println("昵称不能为空");
                }else {
                    pw.println(nickName);
                    break;
                }
            }

            while (true){
                String line = Scanner.nextLine();
                if ("exic".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    public static void main(String[] args) {
        Client cl = new Client();
        cl.start();


    }

    public class ServerHandler implements Runnable{
        public void run(){
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,StandardCharsets.UTF_8);
                BufferedReader bos = new BufferedReader(isr);
                String str;
                while ((str=bos.readLine())!=null){
                    System.out.println(str);
                }
            } catch (IOException e) {
            }
        }
    }
}
